Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
PEGjs | Implement Variable in Parser

I am very beginner to PEGjs I need help to implement variable (identifier) declaration support to my parser.

My input code look like:

a=4;
print a

My PEGjs grammer:

start
=(line)*
line
=left:var"="right:integer";" {left=right;}
/ 
print middle:var {return middle;}
print
="print"
var
=(a-zA-z)+
Integer "integer"
= _ [0-9]+ { return parseInt(text(), 10); }

Expected output: 4

Please help me. #ThanksInAdvance

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

try this:

all
  = _ mn:multiPutN _ pn:printN _ 
  {
    return mn[pn];
  }

multiPutN
  = mp:putN+ _ 
  {
    var r = {};
    mp.forEach(it => {
        r[it[0]]=it[1];
    });
    return r;
  }
  
putN
  = vn:varName _ "=" _ nn:n _ ";" { return [vn, nn]}

printN
  = print _ n:varName _ {return n;}
  
varName
  = [a-zA-Z]+ {return text();}
  
print 
  ="print"

n "integer number"
  = _ [0-9]+ { return parseInt(text(), 10); }
  
_ "whitespace or new line"
  = [ \t\n\r]*

so that code above also support multi variables but can only print one variable. I wrote the grammar based in your example so when assigning variable value you need to put ";" at the end but print var should not need with that

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!